﻿using Microsoft.Xna.Framework;
using MarvinsArena.Core;
using System.Collections.Generic;

namespace BattleEngine2D
{
	public class Camera : BattleEngineCommon.Camera
	{
		public Vector2 Position;
		public Vector2 Screen { get; private set; }

        private bool isFreeMode = false;

        public void Initialize(GraphicsDeviceManager graphics)
		{
			this.Screen = new Vector2(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
		}

		public void UpdateCamera (List<IRobot> robots, Map map)
		{
            //Moving camera in "free" mode
            if (this.TargetIndex == this.EmptyTarget)
            {
                if (!isFreeMode)
                {
                    this.MoveCameraOnDefaultPosition(map);
                    this.isFreeMode = true;
                }
                this.MoveCamera();
            }
            else
            {
                this.MoveCameraOnTarget(robots[this.TargetIndex], map);
                this.isFreeMode = false;
            }
		}

        private void MoveCameraOnDefaultPosition(Map map)
        {
            this.Position.X = (this.Screen.X - map.MapWidth * map.MapScale) / 2;
            this.Position.Y = (this.Screen.Y - map.MapHeight * map.MapScale) / 2;
        }

        private void MoveCamera()
        {
            //Move camera down
            if (this.isMoveDown)
                this.Position.Y += this.Step;

            //Move camera left
            if (this.isMoveLeft)
                this.Position.X -= this.Step;

            //Move camera right
            if (this.isMoveRight)
                this.Position.X += this.Step;

            //Move camera up
            if (this.isMoveUp)
                this.Position.Y -= this.Step;
        }

        private void MoveCameraOnTarget(IRobot target, Map map)
        {
            this.Position.X = this.Screen.X / 2 - (float)target.PositionX;
            this.Position.Y = this.Screen.Y / 2 - (float)target.PositionY;
        }
	}
}
